// http://sourceforge.jp/projects/wrj4p5/wiki/Wrj4P5
import lll.wrj4P5.*;

//http://sourceforge.jp/projects/wrj4p5/wiki/Loc
import lll.Loc.*;

import processing.net.Server;
import processing.net.Client;

import java.util.Iterator;
import java.util.ArrayList;

Wrj4P5 wii;
int port = 19028;
byte zero = 0;
Server server;
ArrayList clients = new ArrayList ();

void setup () 
{
  size ( 320, 240 );
  
  // Starts server on port 19028
  this.server = new Server ( this, this.port );
  
  // The base class for managing the available WiiRemotes and extensions.
  this.wii = new Wrj4P5 ( this );
  this.wii.connect ();
}

void draw () 
{
  if ( this.wii.isConnecting () ) 
  {
    return;
  }
  
  // The model of geometric point with location and geometric calculations.
  Loc cog = this.wii.board.guessCoG ();
  
  // Indicates the x coordinate.
  float x = max ( 0, min ( cog.x, 1 ) );
  
  // Indicates the y coordinate.
  float y = max ( 0, min ( cog.y, 1 ) );
  
  Iterator i = this.clients.iterator ();
  
  while ( i.hasNext () )
  {
    Client c = ( Client ) i.next ();
    
    if ( c.active () == false )
    {
      i.remove ();
    }
    else
    {
      // XML Soccet connected.
      c.write ( x + ";" + y );
      c.write ( zero );
    }
  }
}

void serverEvent ( Server pServer, Client pClient )
{
  println ( "New Client: " + pClient.ip () );
  this.clients.add ( pClient );
}

